package com.laikan.reader.bookfriend.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.PersonalYdzAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ReadVolumesBean;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @category 阅读券信息
 */
@SuppressLint ("HandlerLeak")
public class ReadTicketActivity extends BasicActivity {

    private ListView mListView;

    private ArrayList<ReadVolumesBean> mData;
    private PersonalYdzAdapter mAdapter;
    private ImageView back_tv;
    /**
     * 没有优惠券显示的图片
     */
    //    private ImageView iv_no_coupon;
    private RelativeLayout rl_coupon_info;
    private LinearLayout rl_no_coupon;

    /**
     * 兑换按钮
     */
    private TextView tv_convert;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    private TouchSwipeRefreshLayout mCommentSwipeRefresh;

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.personal_ydz);
        mListView = (ListView)findViewById(R.id.lv_ydz);
        // iv_no_coupon = (ImageView)findViewById(R.id.iv_no_coupon);
        rl_no_coupon = (LinearLayout)findViewById(R.id.rl_no_coupon);
        rl_coupon_info = (RelativeLayout)findViewById(R.id.rl_coupon_info);
        tv_convert = (TextView)findViewById(R.id.tv_convert);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mCommentSwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mCommentSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        mCommentSwipeRefresh.setChildView(mListView);
    }

    @Override
    protected void initData() {
        mData = new ArrayList<ReadVolumesBean>();
        mAdapter = new PersonalYdzAdapter(mContext, mData);
        mListView.setAdapter(mAdapter);
        getData();
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        tv_convert.setOnClickListener(this);
        /*设置pullToRefreshListView的刷新模式，BOTH代表支持上拉和下拉，PULL_FROM_END代表上拉,PULL_FROM_START代表下拉 */
//        ptrLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        // 上拉加载 下拉刷新
        //use TouchSwipeRefreshLayout OnRefreshListener
        mCommentSwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();

            }
        });

        // 打开阅读券信息页面
        rl_coupon_info.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReadTicketActivity.this, ReadTicketIntroduceActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 从网络获取数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mCommentSwipeRefresh.setLoading(false);
                BaseDataBean<BaseListDataBean<ReadVolumesBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ReadVolumesBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (!Constants.RESULT_OK.equals(result.getResult())) {
                        ToastMgr.showShortToast(result.getError_msg());
                    }else {
                        mData = result.getData().getData();

                        if (mData.size() != 0) {
                            //                            iv_no_coupon.setVisibility(View.GONE);
                            mCommentSwipeRefresh.setEnabled(true);
                            rl_no_coupon.setVisibility(View.GONE);
                        }else {
                            //                            iv_no_coupon.setVisibility(View.VISIBLE);
                            mCommentSwipeRefresh.setEnabled(false);
                            rl_no_coupon.setVisibility(View.VISIBLE);
                        }
                        mAdapter.setDatas(mData);
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mCommentSwipeRefresh.setRefreshing(false);
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。38");
            }

            @Override
            public void onFinish() {
                mCommentSwipeRefresh.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_personal_yueduquan);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_personal_yueduquan, map, null, null, requestListener);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:    // 返回
                finish();
                break;

            case R.id.tv_convert:
                Intent intent = new Intent(ReadTicketActivity.this, ConvertReadTicketActivity.class);
                startActivity(intent);
                break;
        }
    }
}
